package com.aloha.boot01.controller;

import com.aloha.boot01.domain.User;
import com.aloha.boot01.service.HelloService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Resource
    private HelloService helloService;

    @PostMapping("/json")
    public Object testJSON(@RequestBody Map<String, String> info) {
        System.out.println(info);
        return info;
    }

    @GetMapping("/info/{id}")
    public User getInfo(@PathVariable("id") Long id) {
        return helloService.getInfo(id);
    }

    @GetMapping("/redirect")
    public void sendRedirect(HttpServletResponse response) throws Exception {
        response.sendRedirect("/hello/info/1001");
        System.out.println("---------------->");
    }


    @GetMapping("/set-cookie")
    public Cookie setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("test-msg", "aloha");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        cookie.setPath("/");
        response.addCookie(cookie);
        return cookie;
    }

    @GetMapping("/del-cookie/v1")
    public Cookie delCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("test-msg", "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return cookie;
    }

    @GetMapping("/del-cookie/v2")
    public Cookie delCookie2(HttpServletResponse response) {
        Cookie cookie = new Cookie("test-msg", "aloha");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return cookie;
    }

    @GetMapping("/cookie")
    public List<Cookie> getCookie(HttpServletRequest request) {
        return Arrays.stream(request.getCookies()).collect(Collectors.toList());
    }
}
